/**
 * Security helper functions for decrypting database credentials
 */
const crypto = require('crypto');

// The secret key used for decryption (same as in your encryption script)
const SECRET_KEY = 'b23c987d5a4b3e9f6c125d4e8f7a9b1c'; 

// Known encrypted values - replace these with actual encrypted values from your test script
const encryptedValues = {
  dbHost: '123abc:456def:789ghi', // Replace with actual encrypted value
  dbName: '234bcd:567efg:890hij', // Replace with actual encrypted value
  dbTable: '345cde:678fgh:901ijk', // Replace with actual encrypted value
  dbUsername: '456def:789ghi:012jkl', // Replace with actual encrypted value
  dbPassword: '567efg:890hij:123klm' // Replace with actual encrypted value
};

/**
 * Decrypt an encrypted string
 */
function decryptValue(encryptedText) {
  try {
    const parts = encryptedText.split(':');
    if (parts.length !== 3) return null; // Not our encrypted format
    
    const iv = Buffer.from(parts[0], 'hex');
    const authTag = Buffer.from(parts[1], 'hex');
    const encryptedData = parts[2];
    
    const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(SECRET_KEY, 'hex'), iv);
    decipher.setAuthTag(authTag);
    
    let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    
    return decrypted;
  } catch (error) {
    // If decryption fails, it's probably not our encrypted value
    return null;
  }
}

/**
 * Process function body to replace encrypted credentials with decrypted values
 */
function processEncryptedCredentials(functionBody) {
  if (!functionBody) return functionBody;
  
  let processedBody = functionBody;
  
  // Check for dynamic pattern matches first (hex:hex:hex)
  const encryptionPattern = /['"]([0-9a-f]+:[0-9a-f]+:[0-9a-f]+)['"]/g;
  let match;
  
  while ((match = encryptionPattern.exec(functionBody)) !== null) {
    const potentialEncrypted = match[1];
    const decrypted = decryptValue(potentialEncrypted);
    
    if (decrypted) {
      // Replace in the function body, keeping the quotes that surrounded it
      const fullMatch = match[0];
      const replacement = fullMatch[0] + decrypted + fullMatch[fullMatch.length - 1];
      processedBody = processedBody.replace(fullMatch, replacement);
    }
  }
  
  // Also check for known encrypted values
  Object.entries(encryptedValues).forEach(([key, encryptedValue]) => {
    if (processedBody.includes(encryptedValue)) {
      const decrypted = decryptValue(encryptedValue);
      if (decrypted) {
        processedBody = processedBody.replace(
          new RegExp(`['"]${encryptedValue}['"]`, 'g'), 
          `"${decrypted}"`
        );
      }
    }
  });
  
  return processedBody;
}

module.exports = {
  decryptValue,
  processEncryptedCredentials,
  encryptedValues
};